<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    :width="width"
    :draggable="draggable"
    :close-on-click-modal="closeOnClickModal"
    :close-on-press-escape="closeOnPressEscape"
    :show-close="showClose"
    :before-close="beforeClose"
    @update:model-value="handleUpdateVisible"
    @close="handleClose"
    @opened="handleOpened"
    @closed="handleClosed"
  >
    <!-- 主要内容插槽 -->
    <slot />
    
    <!-- 底部按钮区域 -->
    <template #footer>
      <div class="dialog-footer">
        <!-- 自定义底部内容插槽 -->
        <slot name="footer">
          <!-- 默认按钮配置 -->
          <template v-if="footerType === 'default'">
            <el-button @click="handleCancel">{{ cancelText }}</el-button>
            <el-button type="primary" @click="handleConfirm" :loading="confirmLoading">
              {{ confirmText }}
            </el-button>
          </template>
          <!-- 只有关闭按钮 -->
          <template v-else-if="footerType === 'close'">
            <el-button @click="handleClose">{{ closeText }}</el-button>
          </template>
          <!-- 只有确定按钮 -->
          <template v-else-if="footerType === 'confirm'">
            <el-button type="primary" @click="handleConfirm" :loading="confirmLoading">
              {{ confirmText }}
            </el-button>
          </template>
        </slot>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElDialog, ElButton } from 'element-plus'

// Props 接口定义
interface Props {
  // 基础属性
  visible: boolean
  title: string
  width?: string | number
  draggable?: boolean
  closeOnClickModal?: boolean
  closeOnPressEscape?: boolean
  showClose?: boolean
  
  // 底部按钮配置
  footerType?: 'default' | 'close' | 'confirm' | 'custom'
  cancelText?: string
  confirmText?: string
  closeText?: string
  confirmLoading?: boolean
  
  // 关闭前回调
  beforeClose?: (done: () => void) => void
}

// 默认属性值
const props = withDefaults(defineProps<Props>(), {
  width: '500px',
  draggable: false,
  closeOnClickModal: false,
  closeOnPressEscape: true,
  showClose: true,
  footerType: 'default',
  cancelText: '取消',
  confirmText: '确定',
  closeText: '关闭',
  confirmLoading: false
})

// 事件定义
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'close': []
  'cancel': []
  'confirm': []
  'opened': []
  'closed': []
}>()

// 处理 visible 更新
const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

// 处理关闭
const handleClose = () => {
  emit('close')
  emit('update:visible', false)
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
  emit('update:visible', false)
}

// 处理确定
const handleConfirm = () => {
  emit('confirm')
}

// 处理打开完成
const handleOpened = () => {
  emit('opened')
}

// 处理关闭完成
const handleClosed = () => {
  emit('closed')
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 当只有一个按钮时居中显示 */
.dialog-footer:has(.el-button:only-child) {
  justify-content: center;
}
</style>
